import React, { FC, useState } from "react"
import styles from "./QuestionCard.module.scss"
import { Button, Space, Divider, Tag, Modal, message, Popconfirm } from "antd"
import { EditOutlined, LineChartOutlined, StarOutlined, CopyOutlined, DeleteOutlined, ExclamationCircleOutlined } from "@ant-design/icons"
import { useNavigate, Link } from "react-router-dom"
import { useRequest } from "ahooks"
import { updateQuestionService, duplicateQuestionService } from "../services/question"

type PropsType = {
    _id: string
    title: string
    isStar: boolean
    isPublished: boolean
    answerCount: number
    createdAt: string
}

const QuestionCard: FC<PropsType> = (props: PropsType) => {
    const { _id, title, isStar, isPublished, answerCount, createdAt } = props
    const nav = useNavigate()
    const { confirm } = Modal

    // 修改标星
    const [isStarState, setIsStarState] = useState(isStar)
    const { run: changeStar, loading: changeStarLoading } = useRequest(
        async () => {
            await updateQuestionService(_id, { isStar: !isStarState })
        },
        {
            // 手动触发（点击按钮）
            manual: true,
            onSuccess() {
                setIsStarState(!isStarState) // 更新state
                console.log(isStarState)
                message.success("更新成功")
            }
        }
    )

    // 复制
    const { loading: duplicateLoading, run: duplicate } = useRequest(
        async () => {
            const data = await duplicateQuestionService(_id)
            return data
        },
        {
            // 手动触发（点击按钮）
            manual: true,
            onSuccess(result) {
                message.success("复制成功")
                // 复制成功会返回一个id
                // 跳转到复制问卷的编辑页面
                console.log(title)

                nav(`/question/edit/${result.id}`)
            }
        }
    )

    // 删除（只是更新删除的状态，并不是真正的删除）
    const [isDeletedState, setIsDeleteState] = useState(false)
    const { loading: deleteLoading, run: deleteQuestion } = useRequest(
        async () => {
            await updateQuestionService(_id, { isDeleted: true })
        },
        {
            manual: true,
            onSuccess() {
                message.success("删除成功")
                setIsDeleteState(true)
            }
        }
    )

    function del() {
        confirm({
            title: "是否确定删除？",
            icon: <ExclamationCircleOutlined />,
            okText: "确定",
            cancelText: "取消",
            onOk: deleteQuestion
        })
    }

    // 如果删除就返回null，否则返回一个jsx片段，删除了就不需要再渲染卡片了
    if (isDeletedState) return null

    return (
        <div className={styles.container}>
            <div className={styles.title}>
                <div className={styles.left}>
                    {/* 如果发布了跳转到统计页面 */}
                    {/* 没有发布就跳转到编辑页面 */}
                    <Link to={isPublished ? `/question/stat/${_id}` : `/quesiton/edit/${_id}`}>
                        <Space>
                            {/* 如果标星了显示icon，并改为红色 */}
                            {isStar && <StarOutlined style={{ color: "red" }} />}
                            {title}
                        </Space>
                    </Link>
                </div>
                <div className={styles.right}>
                    <Space>
                        {isPublished ? <Tag color="success">已发布</Tag> : <Tag color="processing">未发布</Tag>}
                        <span>答卷:{answerCount}</span>
                        <span>{createdAt}</span>
                    </Space>
                </div>
            </div>
            <Divider style={{ margin: "20px 0" }} />
            <div className={styles["button-container"]}>
                <div className={styles.left}>
                    <Space>
                        <Button icon={<EditOutlined />} type="text" onClick={() => nav(`/question/edit/${_id}`)}>
                            编辑问卷
                        </Button>
                        <Button icon={<LineChartOutlined />} type="text" onClick={() => nav(`/question/stat/${_id}`)} disabled={!isPublished}>
                            {/* 如果没有发布就不能统计数据 */}
                            数据统计
                        </Button>
                    </Space>
                </div>
                <div className={styles.right}>
                    <Space>
                        <Button type="text" icon={<StarOutlined />} onClick={changeStar} disabled={changeStarLoading}>
                            {isStarState ? "取消标星" : "标星"}
                        </Button>
                        <Popconfirm title="确定复制该问卷？" okText="确定" cancelText="取消" onConfirm={duplicate}>
                            <Button type="text" icon={<CopyOutlined />} disabled={duplicateLoading}>
                                复制
                            </Button>
                        </Popconfirm>
                        <Button type="text" danger icon={<DeleteOutlined />} onClick={del} disabled={deleteLoading}>
                            删除
                        </Button>
                    </Space>
                </div>
            </div>
        </div>
    )
}

export default QuestionCard
